/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mx.unam.fciencias.ActividadesCulturales.commons;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import mx.unam.fciencias.actividadesculturales.entidades.db.CatalogoInterface;
import org.apache.tapestry5.OptionGroupModel;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.internal.OptionModelImpl;
import org.apache.tapestry5.util.AbstractSelectModel;

/**
 * Selection Model generico para una lista de objetos.
 * @author lumartin
 */
public class CatalogoSelectModel<T extends CatalogoInterface> extends AbstractSelectModel
        implements ValueEncoder<T>, Serializable {

   private List<T> catalogos;

    public CatalogoSelectModel(List<T> catalogos) {
        this.catalogos = catalogos;
    }

    public List<T> getList(){
        return catalogos;
    }

    @Override
    public List<OptionGroupModel> getOptionGroups() {
        return null;
    }

    @Override
    public List<OptionModel> getOptions() {
        List<OptionModel> opciones = new ArrayList<OptionModel>();
        for (T cat : catalogos) {
            OptionModelImpl option =
                    new OptionModelImpl(cat.getNombre(), cat);
            if (cat != null && cat.getNombre() != null) {
                opciones.add(option);
            }
        }
        return opciones;
    }

    @Override
    public String toClient(T value) {
        return Long.toString(value.getId());
    }

    @Override
    public T toValue(String clientValue) {
        for (T cat : catalogos) {
            if (Long.toString(cat.getId()).equals(clientValue)) {
                return cat;
            }
        }
        return null;
    }
}
